//
//  XFAudioViewController.m
//  test
//
//  Created by mac on 2017/8/30.
//  Copyright © 2017年 mac. All rights reserved.

// <cmd-en>:JD（Joy Buy）|TMall Mart|YHD（1 HaoDian）|H&S（head&shoulders）|Pantene|Rejoice|VS（Sasoon）|Ciairol|SK-II|Olay|Safeguard|Frebreze|Ariel|Tide|Sarasa|Oral-B|Braun|Gillette|Crest|Whisper|Pampers|Beijing|Shanghai|Guangzhou|Chengdu|Wuhan|Tianjin|Jinan|Shenyang|Jinhua|Suzhou|Hangzhou|Nanjing|Jinjiang|Xi'an|Huiyang|Zhengzhou;
//
#import "XFAudioViewController.h"

#import "iflyMSC/IFlySpeechUtility.h"
#import "iflyMSC/IFlySpeechConstant.h"
#import "iflyMSC/IFlySpeechRecognizer.h"
#import "iflyMSC/IFlyDataUploader.h"
#import "iflyMSC/IFlyResourceUtil.h"
#import "iflyMSC/IFlySpeechError.h"

#import "ISRDataHelper.h"

#define kOFFSET_FOR_KEYBOARD 110.0
#define GRAMMAR_TYPE_BNF    @"bnf"



@interface XFAudioViewController()
{
    UILabel *label;
}

@end

@implementation XFAudioViewController

- (instancetype) init
{
    self = [super init];
    if (!self) {
        return nil;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.curResult = [[NSMutableString alloc]init];
    NSLog(@"初始化成功");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.grammarType = GRAMMAR_TYPE_BNF;
    
    [self createView];
    
}

-(void)createView{
    self.view.backgroundColor =[UIColor whiteColor];
    label = [[UILabel alloc]initWithFrame:CGRectMake(0,50,self.view.frame.size.width,200)];
    label.text= @"Hello iSmart!";
    label.textColor = [UIColor orangeColor];
    label.font=[UIFont
                fontWithName:@"Arial-BoldItalicMT"
                size:32];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.shadowColor = [UIColor blackColor];
    [self.view addSubview:label];
    
    UIButton *btn_upload = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect frame0;
    frame0.size.width = 150;
    frame0.size.height = 40;
    frame0.origin.x = self.view.frame.size.width / 2 - 75;
    frame0.origin.y = self.view.frame.size.height / 2;
    [btn_upload setFrame:frame0];
    [btn_upload setTitle:@"build bnf" forState:UIControlStateNormal];
    [btn_upload addTarget:self action:@selector(btn_upload) forControlEvents:UIControlEventTouchUpInside];
    [btn_upload setBackgroundColor:[UIColor orangeColor]];
    [btn_upload setAlpha:0.8];
    btn_upload.layer.cornerRadius=5;
    [btn_upload setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:btn_upload];
    
    UIButton *btn_start = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect frame;
    frame.size.width = 150;
    frame.size.height = 40;
    frame.origin.x = self.view.frame.size.width / 2 - 75;
    frame.origin.y = self.view.frame.size.height / 2 + 50;
    [btn_start setFrame:frame];
    [btn_start setTitle:@"start" forState:UIControlStateNormal];
    [btn_start addTarget:self action:@selector(btn_start) forControlEvents:UIControlEventTouchUpInside];
    [btn_start setBackgroundColor:[UIColor orangeColor]];
    [btn_start setAlpha:0.8];
    btn_start.layer.cornerRadius=5;
    [btn_start setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:btn_start];
    
    UIButton *btn_stop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect frame2;
    frame2.size.width = 150;
    frame2.size.height = 40;
    frame2.origin.x = self.view.frame.size.width / 2 - 75;
    frame2.origin.y = self.view.frame.size.height / 2 + 100;
    [btn_stop setFrame:frame2];
    [btn_stop setTitle:@"stop" forState:UIControlStateNormal];
    [btn_stop addTarget:self action:@selector(btn_stop) forControlEvents:UIControlEventTouchUpInside];
    [btn_stop setBackgroundColor:[UIColor orangeColor]];
    [btn_stop setAlpha:0.8];
    btn_stop.layer.cornerRadius=5;
    [btn_stop setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:btn_stop];
}
-(void)btn_start{
    self.grammarType = GRAMMAR_TYPE_BNF;
    //启动语法识别
    /*BOOL ret = [IFlySpeechRecognizer.sharedInstance startListening];
    if (ret) {
        [_stopBtn setEnabled:YES];
        [_cancelBtn setEnabled:YES];
        [_startBtn setEnabled:NO];
        [_uploadBtn setEnabled:NO];
        [_engineBtn setEnabled:NO];
        self.isCanceled = NO;
        [self.curResult setString:@""];
    }else{
        NSLog(@"启动识别服务失败，请稍后重试");
    }*/
    //启动识别
    [_iFlySpeechRecognizer startListening];
}

-(void)btn_upload{
    [_iFlySpeechRecognizer stopListening];
    
    [_uploadBtn setEnabled:NO];
    [_startBtn setEnabled:NO];
    [_engineBtn setEnabled:NO];
    [_stopBtn setEnabled:NO];
    [_cancelBtn setEnabled:NO];
    //构建语法
    [self buildGrammer];
}

-(void)btn_stop{
    //停止录音
    [IFlySpeechRecognizer.sharedInstance stopListening];
    [_resultView resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)buildGrammer{
    NSString *appPath = [[NSBundle mainBundle] resourcePath];
    //获取识别对象单例
    _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    //设置协议委托对象
    _iFlySpeechRecognizer.delegate = self;
    //设置引擎类型，cloud 或者 local
    [_iFlySpeechRecognizer setParameter:@ "local" forKey:[IFlySpeechConstant ENGINE_TYPE]];
    //语法类型，本地是 bnf，在线识别是 abnf
    [_iFlySpeechRecognizer setParameter:@ "bnf" forKey:[IFlyResourceUtil GRAMMARTYPE]];
    
    NSString *documentsPath = nil;
    NSArray *appArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([appArray count] > 0) {
        documentsPath = [appArray objectAtIndex:0];
    }
    NSString *grammBuildPath = [documentsPath stringByAppendingString:@"/grm"];
    [_iFlySpeechRecognizer setParameter:grammBuildPath forKey:[IFlyResourceUtil GRM_BUILD_PATH]];
    //设置引擎资源文件路径，如 demo 中的 aitalkResource 中的 common.mp3
    NSString *aitalkResourcePath = [[NSString alloc] initWithFormat:@"fo|%@/aitalkResource/common.mp3",appPath];
    [_iFlySpeechRecognizer setParameter:aitalkResourcePath forKey:[IFlyResourceUtil ASR_RES_PATH]];
    //启动 asr 识别引擎
    [[IFlySpeechUtility getUtility] setParameter:@"asr" forKey:[IFlyResourceUtil ENGINE_START]];
    //编译语法文件（注意 grammarType 参数的区别）
    //读取本地 bnf 语法文件内容
    NSString *bnfFilePath = [[NSString alloc] initWithFormat:@"%@/bnf/call.bnf",appPath];
    NSString* grammarContent = [self readFile:bnfFilePath];
    //调用语法编译接口
    [_iFlySpeechRecognizer buildGrammarCompletionHandler:^(NSString * grammerID, IFlySpeechError *error){
        dispatch_async(dispatch_get_main_queue(), ^{
             if (![error errorCode]) {
                label.text = @"成功";
             }else{
                label.text = @"失败";
                NSLog(@"失败:%@",[error errorDesc]);
             }
            //设置 grammerID
            [_iFlySpeechRecognizer setParameter:grammerID forKey:[IFlySpeechConstant LOCAL_GRAMMAR]];
        });
    }grammarType:self.grammarType grammarContent:grammarContent];
    
}


- (void) onResults:(NSArray *) results isLast:(BOOL) isLast{
    NSMutableString * resultString = [[NSMutableString alloc]init];
    NSDictionary *dic = results[0];
    NSArray *keys = [dic allKeys];
    for (NSString *key in keys) {
        NSString *res = [ISRDataHelper stringFromAsr:key];
        [resultString appendString:res];
    }
    if (isLast) {
        NSLog(@"result is:%@",self.curResult);
    }
    NSLog(@"============%@",resultString);
    [self.curResult appendString:resultString];
  
}
//会话结束回调
- (void) onError:(IFlySpeechError*) error{
    NSLog(@"会话结束回调");
    if (self.isCanceled) {
        label.text = @"识别取消";
    }else if (error.errorCode ==0 ) {
        if (self.curResult.length==0 || [self.curResult hasPrefix:@"nomatch"]) {
            label.text = @"无匹配结果";
        }else{
            label.text = self.curResult;
            _resultView.text = _curResult;
        }
    }else{
        label.text = @"发生错误";
    }
    
    [self.curResult setString:@""];
    
    //[_iFlySpeechRecognizer startListening];
    [_stopBtn setEnabled:NO];
    [_cancelBtn setEnabled:NO];
    [_uploadBtn setEnabled:YES];
    [_startBtn setEnabled:YES];
    [_engineBtn setEnabled:YES];
}
//录音音量回调
- (void) onVolumeChanged: (int)volume{
    NSLog(@"录音音量回调");
}
//录音开始回调
- (void) onBeginOfSpeech{
    NSLog(@"录音开始回调");
    label.text = @"录音中...";
}
//录音结束回调
- (void) onEndOfSpeech{
    NSLog(@"录音结束回调");
}
//会话取消回调
- (void) onCancel{
    NSLog(@"会话取消回调");
}










/*
 *****文件读取*****
 */
-(NSString *)readFile:(NSString *)filePath
{
    NSData *reader = [NSData dataWithContentsOfFile:filePath];
    return [[NSString alloc] initWithData:reader
                                 encoding:NSUTF8StringEncoding];
}

@end
